package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.RecordAdapter;
import flc.ast.databinding.ActivityDnsBinding;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.Content;
import stark.common.basic.device.NetUtil;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.inf.IRetCallback;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class DnsActivity extends BaseAc<ActivityDnsBinding> {

    private String host;
    private RecordAdapter recordAdapter;

    @Override
    protected int onCreate() {
        return R.layout.activity_dns;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivDnsBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivDnsShare.setOnClickListener(this);
        mDataBinding.tvStart.setOnClickListener(this);
        mDataBinding.tvClear.setOnClickListener(this);
        mDataBinding.tvScan.setOnClickListener(this);
        mDataBinding.ivHostClear.setOnClickListener(this);

        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(this);
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);
        mDataBinding.rvRecordList.setLayoutManager(layoutManager);
        recordAdapter = new RecordAdapter();
        mDataBinding.rvRecordList.setAdapter(recordAdapter);
        recordAdapter.addChildClickViewIds(R.id.ivRecordItemDelete);
        recordAdapter.setOnItemClickListener(this);
        recordAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivDnsShare://分享
                String text = mDataBinding.tvDnsResult.getText().toString().trim();
                if (TextUtils.isEmpty(text)) return;
                IntentUtil.shareText(mContext, text);
                break;
            case R.id.ivHostClear://域名清空
                mDataBinding.etHost.setText("");
                break;
            case R.id.tvStart://开始
                host = mDataBinding.etHost.getText().toString();
                if (TextUtils.isEmpty(host)) {
                    mDataBinding.etHost.requestFocus();
                    ToastUtils.showShort(getString(R.string.please_input_url));
                    return;
                }
                handleClickParseDns();
                saveRecord();
                getRecord();
                break;
            case R.id.tvClear://清空
                mDataBinding.etHost.setText("");
                mDataBinding.tvDnsResult.setText("");
                break;
            case R.id.tvScan://扫描
                getCameraPermission();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        mDataBinding.etHost.setText(recordAdapter.getItem(position));
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivRecordItemDelete:
                List<String> listSp = AppSpUtils.getDnsRecordList();
                listSp.remove(position);
                AppSpUtils.saveDnsRecordList(listSp);
                getRecord();
        }
    }

    @Override
    protected void initData() {
        getRecord();
    }

    private void handleClickParseDns() {
        host = mDataBinding.etHost.getText().toString().trim();
        if (TextUtils.isEmpty(host)) {
            ToastUtils.showShort(getString(R.string.please_input_domain));
            return;
        }
        NetUtil.getAllHostAddressByName(host, new IRetCallback<List<String>>() {
            @Override
            public void onResult(List<String> result) {
                StringBuilder builder = new StringBuilder();
                builder.append(getString(R.string.dns_text) + "\n");
                if (result != null && result.size() > 0) {
                    for (String address : result) {
                        builder.append(host + "/" + address + "\n");
                    }
                } else {
                    builder.append(R.string.no_dns);
                }
                mDataBinding.tvDnsResult.setText(builder.toString());
            }
        });
    }

    private void saveRecord() {
        List<String> listSave = new ArrayList<>();
        listSave.add(host);
        List<String> listSp = AppSpUtils.getDnsRecordList();
        if (listSp != null && listSp.size() > 0) {
            listSp.remove(host);
            listSp.add(0, host);
            AppSpUtils.saveDnsRecordList(listSp);
        } else {
            AppSpUtils.saveDnsRecordList(listSave);
        }
    }

    private void getRecord() {
        List<String> listSp = AppSpUtils.getDnsRecordList();
        if (listSp != null && listSp.size() > 0) {
            recordAdapter.setList(listSp);
            mDataBinding.rvRecordList.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.rvRecordList.setVisibility(View.GONE);
        }
    }

    private void getCameraPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA)
                .reqPermissionDesc(getString(R.string.get_scan_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        Intent intent = new Intent(DnsActivity.this, ScanQrActivity.class);
                        startActivityForResult(intent, Content.DNS_SCAN);
                    }
                }).request();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == Content.DNS_SCAN) {
            String result = data.getStringExtra(Content.result);
            mDataBinding.etHost.setText(result);
        }
    }

}